
/**
  ******************************************************************************
  * Copyright 2021 The Microbee Authors. All Rights Reserved.
  * 
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
  * 
  * http://www.apache.org/licenses/LICENSE-2.0
  * 
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
  * 
  * @file       sensor_rf_benewake.c
  * @author     baiyang
  * @date       2023-2-9
  ******************************************************************************
  */

/*----------------------------------include-----------------------------------*/
#include "sensor_rf_benewake.h"
#if MB_RANGEFINDER_BENEWAKE_ENABLED

#include <common/utility/sparse-endian.h>
/*-----------------------------------macro------------------------------------*/
#define BENEWAKE_FRAME_HEADER 0x59
#define BENEWAKE_FRAME_LENGTH 9
#define BENEWAKE_DIST_MAX_CM 32768
#define BENEWAKE_OUT_OF_RANGE_ADD_CM 100
/*----------------------------------typedef-----------------------------------*/

/*---------------------------------prototype----------------------------------*/
static MAV_DISTANCE_SENSOR _get_mav_distance_sensor_type(sensor_rf_backend_const_t rf_backend);
static bool get_reading(sensor_rf_backend_t rf_backend, float *reading_m);
/*----------------------------------variable----------------------------------*/
static struct sensor_rf_backend_ops ops_backend = {.rf_backend_destructor  = NULL,
                                                   .update      = NULL,
                                                   .init_serial = NULL,
                                                   .handle_msg  = NULL,
                                                   .max_distance_cm = NULL,
                                                   .min_distance_cm = NULL,
                                                   .get_temp    = NULL,
                                                   .get_signal_quality_pct = NULL,
                                                   ._get_mav_distance_sensor_type = _get_mav_distance_sensor_type};

static struct sensor_rf_backend_ser_ops ops_backend_ser = {.initial_baudrate = NULL,
                                                   .rx_bufsize       = NULL,
                                                   .tx_bufsize       = NULL,
                                                   .get_reading      = get_reading,
                                                   .read_timeout_ms  = NULL};
/*-------------------------------------os-------------------------------------*/

/*----------------------------------function----------------------------------*/
void sensor_rf_backend_benewake_ctor(sensor_rf_benewake_t rf_backend_benewake,
                                    sensor_rf_benewake_ops_t _ops_benewake,
                                    sensor_rf_backend_ser_ops_t _ops_ser,
                                    sensor_rf_backend_ops_t _ops,
                                    sensor_rf_state_t _state, sensor_rf_params_t _params,
                                    const char *name)
{
    if (_ops_ser == NULL) {
        _ops_ser = &ops_backend_ser;
    }

    if (_ops == NULL) {
        _ops = &ops_backend;
    }

    sensor_rf_bind_backend_ser_function(_ops_ser, &ops_backend_ser);
    sensor_rf_bind_backend_function(_ops, &ops_backend);

    rf_backend_benewake->ops_benewake = _ops_benewake;

    sensor_rf_backend_serial_ctor(&rf_backend_benewake->backend, _ops_ser, _ops, _state, _params, name);
}

void sensor_rf_bind_backend_ser_function(sensor_rf_backend_ser_ops_t ops_frontend, sensor_rf_backend_ser_ops_t ops_backend)
{
    if (ops_frontend == ops_backend) {
        return;
    }

    if (ops_frontend->get_reading == NULL && ops_backend->get_reading != NULL) {
        ops_frontend->get_reading = ops_backend->get_reading;
    }
}

static MAV_DISTANCE_SENSOR _get_mav_distance_sensor_type(sensor_rf_backend_const_t rf_backend)
{
    return MAV_DISTANCE_SENSOR_LASER;
}

// format of serial packets received from benewake lidar
//
// Data Bit             Definition      Description
// ------------------------------------------------
// byte 0               Frame header    0x59
// byte 1               Frame header    0x59
// byte 2               DIST_L          Distance (in cm) low 8 bits
// byte 3               DIST_H          Distance (in cm) high 8 bits
// byte 4               STRENGTH_L      Strength low 8 bits
// bute 4 (TF03)        (Reserved)
// byte 5               STRENGTH_H      Strength high 8 bits
// bute 5 (TF03)        (Reserved)
// byte 6 (TF02)        SIG             Reliability in 8 levels, 7 & 8 means reliable
// byte 6 (TFmini)      Distance Mode   0x02 for short distance (mm), 0x07 for long distance (cm)
// byte 6 (TF03)        (Reserved)
// byte 7 (TF02 only)   TIME            Exposure time in two levels 0x03 and 0x06
// byte 8               Checksum        Checksum byte, sum of bytes 0 to bytes 7

// distance returned in reading_m, signal_ok is set to true if sensor reports a strong signal
static bool get_reading(sensor_rf_backend_t rf_backend, float *reading_m)
{
    sensor_rf_backend_ser_const_t rf_backend_ser = (sensor_rf_backend_ser_const_t)rf_backend;
    sensor_rf_benewake_t rf_backend_benewake = (sensor_rf_benewake_t)rf_backend;

    if (rf_backend_ser->uart == NULL) {
        return false;
    }

    float sum_cm = 0;
    uint16_t count = 0;
    uint16_t count_out_of_range = 0;

    // read any available lines from the lidar
    uint16_t nbytes = SerialManager_rx_available(rf_backend_ser->uart);
    while (nbytes-- > 0) {
        int16_t r = SerialManager_read_byte(rf_backend_ser->uart);
        if (r < 0) {
            continue;
        }
        uint8_t c = (uint8_t)r;
        // if buffer is empty and this byte is 0x59, add to buffer
        if (rf_backend_benewake->linebuf_len == 0) {
            if (c == BENEWAKE_FRAME_HEADER) {
                rf_backend_benewake->linebuf[rf_backend_benewake->linebuf_len++] = c;
            }
        } else if (rf_backend_benewake->linebuf_len == 1) {
            // if buffer has 1 element and this byte is 0x59, add it to buffer
            // if not clear the buffer
            if (c == BENEWAKE_FRAME_HEADER) {
                rf_backend_benewake->linebuf[rf_backend_benewake->linebuf_len++] = c;
            } else {
                rf_backend_benewake->linebuf_len = 0;
            }
        } else {
            // add character to buffer
            rf_backend_benewake->linebuf[rf_backend_benewake->linebuf_len++] = c;
            // if buffer now has 9 items try to decode it
            if (rf_backend_benewake->linebuf_len == BENEWAKE_FRAME_LENGTH) {
                // calculate checksum
                uint8_t checksum = 0;
                for (uint8_t i=0; i<BENEWAKE_FRAME_LENGTH-1; i++) {
                    checksum += rf_backend_benewake->linebuf[i];
                }
                // if checksum matches extract contents
                if (checksum == rf_backend_benewake->linebuf[BENEWAKE_FRAME_LENGTH-1]) {
                    // calculate distance
                    uint16_t dist = ((uint16_t)rf_backend_benewake->linebuf[3] << 8) | rf_backend_benewake->linebuf[2];
                    if (dist >= BENEWAKE_DIST_MAX_CM || dist == (uint16_t)(sensor_rf_model_dist_max_cm(rf_backend))) {
                        // this reading is out of range. Note that we
                        // consider getting exactly the model dist max
                        // is out of range. This fixes an issue with
                        // the TF03 which can give exactly 18000 cm
                        // when out of range
                        count_out_of_range++;
                    } else if (!sensor_rf_has_signal_byte(rf_backend)) {
                        // no signal byte from TFmini so add distance to sum
                        sum_cm += dist;
                        count++;
                    } else {
                        // TF02 provides signal reliability (good = 7 or 8)
                        if (rf_backend_benewake->linebuf[6] >= 7) {
                            // add distance to sum
                            sum_cm += dist;
                            count++;
                        } else {
                            // this reading is out of range
                            count_out_of_range++;
                        }
                    }
                }
                // clear buffer
                rf_backend_benewake->linebuf_len = 0;
            }
        }
    }

    if (count > 0) {
        // return average distance of readings
        *reading_m = (sum_cm * 0.01f) / count;
        return true;
    }

    if (count_out_of_range > 0) {
        // if only out of range readings return larger of
        // driver defined maximum range for the model and user defined max range + 1m
        *reading_m = MAX(sensor_rf_model_dist_max_cm(rf_backend), sensor_rf_max_distance_cm(rf_backend) + BENEWAKE_OUT_OF_RANGE_ADD_CM) * 0.01f;
        return true;
    }

    // no readings so return false
    return false;
}

/*------------------------------------test------------------------------------*/
#endif

